<?php


namespace backend\controllers;


use common\models\Category;
use yii\web\Controller;
use yii\web\Response;

class CategoryController extends Controller
{
//        protected $actions = [''];
//    protected $mustlogin = [ 'add', 'mod', 'del', 'rename', 'delete'];
    public function actionAdd()
    {

        $model = new Category();
        if (\Yii::$app->request->isPost) {
            if ($model->add(\Yii::$app->request->post())) {
                \Yii::$app->session->setFlash('info', '添加成功');
            }
        }
        $cates = $model->getData();
        $data = $model->getTree($cates);

        $list = $model->getOption($data);

        return $this->render('add', ['model' => $model, 'list' => $list]);
    }

    public function actionCates()
    {
        $model = new Category();
        $page = \Yii::$app->request->get('page');
        $perpage = \Yii::$app->request->get('per-page');

        $data = $model->getPrimaryCate();
        return $this->render('cates', ['pager' => $data['pages'],'page'=>$page,'perpage'=>$perpage]);
    }

    public function actionDel()
    {
        try {
            $id = \Yii::$app->request->get('cateid');
            if (empty($id)) {
                throw  new \Exception('参数错误');
            }
            $model = new Category();
            $data = Category::find()->where(['parentid' => $id])->all();
            if ($data) {
                throw  new \Exception('该分类下有子类，不可删除');
            }
            if(!$model->deleteAll(['cateid' => $id]))
            {
                throw  new \Exception('删除失败');
            }else{
                \Yii::$app->session->setFlash('info','删除成功');
            }
        } catch (\Exception $e) {
            \Yii::$app->session->setFlash('info',$e->getMessage());

        }
       $this->redirect(['category/cates']);
    }

    public function actionMod()
    {
        $id = \Yii::$app->request->get('cateid');
        $model = Category::find()->where(['cateid' => $id])->one();
        if (\Yii::$app->request->isPost) {
            $data = \Yii::$app->request->post();
            if ($model->load($data) && $model->save()) {
                \Yii::$app->session->setFlash('info', '修改成功');
            }
        }
        $cates = $model->getData();
        $data = $model->getTree($cates);
        $list = $model->getOption($data);
        unset($list[$id]);
        return $this->render('add', ['model' => $model, 'list' => $list]);
    }
    public function actionTree()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $model = new Category();
        $data = $model->getPrimaryCate();
        if (empty($data))
        {
            return [];
        }
        return $data['data'];
    }

}